﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;

namespace LEE.AspNetCore.Extensions.Attributes
{
    /// <summary>
    /// 重写api返回结果数据结构
    /// </summary>
    public class ApiResultAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 自定义验证方法，如果返回false则重写Api结果
        /// </summary>
        protected event Func<ControllerActionDescriptor, bool> Verify;

        public override Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor && Verify?.Invoke(controllerActionDescriptor) == false)
            {
                return base.OnResultExecutionAsync(context, next);
            }

            if (context.Result is ObjectResult objectResult)
            {
                var message = string.Empty;
                if (objectResult.Value is ValidationProblemDetails errorEntity) //是否是参数验证错误
                {
                    message = errorEntity.Errors.FirstOrDefault().Value.FirstOrDefault();
                }
                context.Result = new JsonResult(new ApiResult<object>
                {
                    Success = !objectResult.StatusCode.HasValue || objectResult.StatusCode.Value == 200,
                    Code = objectResult.StatusCode ?? 200,
                    Result = objectResult.Value,
                    Message = message
                });
            }
            else if (context.Result is EmptyResult emptyResult)
            {
                context.Result = new JsonResult(new ApiResult
                {
                    Success = true,
                    Code = 200,
                    Message = ""
                });
            }
            return base.OnResultExecutionAsync(context, next);

        }
    }
}
